package com.flycent.fanbao.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;

/**
 * @author fbl
 */
public class ImageUtil {


	public static byte[] getImageByte(String url){

		InputStream in = null;  
		BufferedOutputStream out = null;  
		try {  
			in = new BufferedInputStream(new URL(url).openStream(), 2*1024);  
			final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();  
			out = new BufferedOutputStream(dataStream, 2*1024);  
			copy(in, out);  
			out.flush();  
			byte[] data = dataStream.toByteArray();  
			return data;  
		}  
		catch (IOException e){  
			e.printStackTrace();  
			return null;  
		}  

	}



	/** 
	 * 得到本地或者网络上的bitmap url - 网络或者本地图片的绝对路径,比如: 
	 *  
	 * A.网络路径: url="http://blog.foreverlove.us/girl2.png" ; 
	 *  
	 * B.本地路径:url="file://mnt/sdcard/photo/image.png"; 
	 *  
	 * C.支持的图片格式 ,png, jpg,bmp,gif等等 
	 *  
	 * @param url  
	 * @return BitMap
	 */  
	public static Bitmap GetLocalOrNetBitmap(String url) {  
		Bitmap bitmap = null;  
		InputStream in = null;  
		BufferedOutputStream out = null;  
		try {  
			in = new BufferedInputStream(new URL(url).openStream(), 2*1024);  
			final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();  
			out = new BufferedOutputStream(dataStream, 2*1024);  
			copy(in, out);  
			out.flush();  
			byte[] data = dataStream.toByteArray();  
			bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);  
			data = null;  
			return bitmap;  
		}  
		catch (IOException e){  
			e.printStackTrace();  
			return null;  
		}  
	} 

	private static void copy(InputStream in, OutputStream out)
			throws IOException {
		byte[] b = new byte[2*1024];
		int read;
		while ((read = in.read(b)) != -1) {
			out.write(b, 0, read);
		}
	}
	
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
	    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
	        bitmap.getHeight(), Config.ARGB_8888);
	    Canvas canvas = new Canvas(output);

	    final int color = 0xff424242;
	    final Paint paint = new Paint();
	    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
	    final RectF rectF = new RectF(rect);
	    final float roundPx = 12;

	    paint.setAntiAlias(true);
	    canvas.drawARGB(0, 0, 0, 0);
	    paint.setColor(color);
	    canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

	    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
	    canvas.drawBitmap(bitmap, rect, rect, paint);

	    return output;
	}


}
